'use strict';
var _ = require('lodash');
var urllib = require('urllib');
var fs = require('fs');
var thunkify = require('thunkify');
var writeFile = thunkify(fs.writeFile);
var unlink = thunkify(fs.unlink);
var exists = thunkify(fs.exists);
var request = thunkify(urllib.request);
var async = require('async');

module.exports.passEncode = function(pass){
  var crypto = require('crypto');
  var md5 = crypto.createHash('md5');
  var salt = "abcdefghijklmnopqrstuvwxyz";
  md5.update(pass+salt);
  pass = md5.digest('hex');
  return pass;
};

module.exports.isLogin = function(self){
  var session = self.session;
  if(!_.has(session,'login_qeeniao')){
    return false;
  }

  if(!_.has(session['login_qeeniao'],'login_on')){
    return false;
  }

  if(!_.has(session['login_qeeniao'],'id') || !session['login_qeeniao']['id']){
    return false;
  }

  return session['login_qeeniao']['login_on'];
};

module.exports.getLoginUID = function(self){
  var session = self.session;
  return session['login_qeeniao']['id'];
};

/**
 * 删除七牛的文件
 * @param  {[type]} key [description]
 * @return {[type]}     [description]
 */
module.exports.deleteQiniuFile = function(key){
  return new Promise(function(resolve,reject){
    var qiniu = require('qiniu');

    qiniu.conf.ACCESS_KEY = 'd_ZwT4XNzBpnxsSpn9erC9tWoPXyI_uK7kzWFET3'
    qiniu.conf.SECRET_KEY = 'RUGMtaUGX4o7DO2_qa4B27Z1rSZdZmbKn0hdP4vS'

    var bucketname = 'qeeniao-mobile';

    //判断是否已经上传
    var client = new qiniu.rs.Client();
    client.stat(bucketname, key, function(err, ret) {
      if (!err) {
        client.remove(bucketname, key, function(err, ret) {
          if (!err) {
            resolve({'success':true,'msg':'操作成功','ret':ret});
          } else {
            reject(err);
          }
        })
      } else {
        reject(err);
      }
    });
  });
}

module.exports.donwloadArchiveFile = function *(task,task_item){
  var member;
  var i = 0;
  while(member = task_item[i]){
    if(!member.attributes.image_url){
      i++;
      continue;
    }

    var file = '';
    if(member.attributes.image_url.startsWith('huanping')){
      file = __dirname + '/../static/upload/' + member.attributes.image_url;
      var image_res = yield request('http://7u2r0u.com2.z0.glb.qiniucdn.com/'+member.attributes.image_url,{timeout:50000});
      yield writeFile(file,image_res[0]);
    }
    i++;
  }
}

module.exports.archive = function(task,task_item){
  return new Promise(function(resolve,reject){
    var fs = require('fs');
    var Archiver = require('archiver');
    var archive = Archiver('zip');
    var upload_filename = __dirname + '/../static/upload/'+task.attributes.name+'.zip';
    var output = fs.createWriteStream(upload_filename);

    output.on('close', function() {
      resolve({'success':true,'path':upload_filename});
    });

    archive.on('error', function(err) {
      reject({'success':false,'error':err});
    });

    archive.pipe(output);

    var i = 0;
    var member;
    while(member = task_item[i]){
      if(!member.attributes.image_url){
        i++;
        continue;
      }

      var file = '';
      if(member.attributes.image_url.startsWith('/upload')){
        file = __dirname + '/../static/'+member.attributes.image_url;
      }else if(member.attributes.image_url.startsWith('huanping')){
        file = __dirname + '/../static/upload/' + member.attributes.image_url;
      }

      archive.append(fs.createReadStream(file),{ name: member.attributes.name +'.png' });

      i++;
    }

    archive.finalize();
  });
};

module.exports.deleteArchiveFile = function *(task,task_item){
  var member;
  var i = 0;
  while(member = task_item[i]){
    if(!member.attributes.image_url){
      i++;
      continue;
    }

    var file = '';
    if(member.attributes.image_url.startsWith('huanping')){
      file = __dirname + '/../static/upload/' + member.attributes.image_url;
      var res = yield this.existsFile(file);
      if(res){
        yield unlink(file);
      }
    }
    i++;
  }
}

module.exports.readFile = function(path){
  return new Promise(function(resolve,reject){
    var fs = require('fs');
    fs.readFile(path,function(err,res){
      if(err){
        return reject(err);
      }
      resolve(res);
    });
  });
};

module.exports.existsFile = function(path){
  return new Promise(function(resolve,reject){
    fs.exists(path,function(res){
      if(res){
        return resolve({'success':true});
      }else{
        return resolve({'success':false});
      }

      reject(new Error('文件检测失败!'));
    });
  });
};

/**
 * 上传七牛文件
 * @return {[type]} [description]
 */
module.exports.qiniuUploadImage = function(body,key){
  return new Promise(function(resolve,reject){
    var qiniu = require('qiniu');

    qiniu.conf.ACCESS_KEY = 'd_ZwT4XNzBpnxsSpn9erC9tWoPXyI_uK7kzWFET3'
    qiniu.conf.SECRET_KEY = 'RUGMtaUGX4o7DO2_qa4B27Z1rSZdZmbKn0hdP4vS'

    var bucketname = 'qeeniao-mobile';

    //判断是否已经上传
    var client = new qiniu.rs.Client();
    client.stat(bucketname, key, function(err, ret) {
      if (!err) {
        client.remove(bucketname, key, function(err, ret) {
          if (!err) {
            //token 生成
            var putPolicy = new qiniu.rs.PutPolicy(bucketname);
            var uptoken = putPolicy.token();

            var extra = new qiniu.io.PutExtra();

            qiniu.io.put(uptoken, key, body, extra, function(err, ret) {
              if (!err) {
                // ret.key & ret.hash
                resolve(ret);
              } else {
                reject(err);
                // 上传失败， 处理返回代码
                // http://developer.qiniu.com/docs/v6/api/reference/codes.html
              }
            });

          } else {
            reject(err);
          }
        })
      } else {
        //token 生成
        var putPolicy = new qiniu.rs.PutPolicy(bucketname);
        var uptoken = putPolicy.token();

        var extra = new qiniu.io.PutExtra();

        qiniu.io.put(uptoken, key, body, extra, function(err, ret) {
          if (!err) {
            // ret.key & ret.hash
            resolve(ret);
          } else {
            reject(err);
            // http://developer.qiniu.com/docs/v6/api/reference/codes.html
          }
        });
      }
    });
  });
}


/**
 * 随机数
 * @return {[type]} [description]
 */
module.exports.random = function(){
  var crypto = require('crypto');
  var md5sum = crypto.createHash('md5');
  var t = Math.random();
  t = t+(new Date()).getTime() + '';
  t = t.replace(/\./g,'#');
  md5sum.update(t);
  t = md5sum.digest('hex');
  return t;
}